package cn.edu.upc.letao.util;

import cn.edu.upc.letao.model.ReturnMessage;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;

/**
 * Created by 风飞扬 on 2017/4/26.
 * 这是文件上传的工具类
 */
@Component
public class MyFileUpload {

    @Value("${qiniu.cheney.AK}")
    public  String accessKey;

    @Value("${qiniu.cheney.SK}")
    public  String secretKey;

    @Value("${qiniu.cheney.bucket}")
    public String bucket;

    @Value("${qiniu.cheney.domain}")
    public String domain;

    //多文件上传
    public ReturnMessage multiFileUpload(List<MultipartFile> mfs){
        ReturnMessage returnMessage = new ReturnMessage();
        if(mfs==null||mfs.size()==0){
            returnMessage.id = 1;//失败
            returnMessage.message = "文件不能为空";
        }
        StringBuffer sb = new StringBuffer();
        for (MultipartFile file:mfs){
            if(!file.isEmpty()){//文件不为空
                try{
                    byte[] bytes = file.getBytes();
                    //获取文件名并且重命名保证唯一性
                    String originalFilename = file.getOriginalFilename();
                    String newFileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
                    //调用上传api
                    String temp = uploadFileToQiNiu(bytes, newFileName);
                    if(temp != null){
                        sb.append(temp);
                        sb.append(",");
                    }
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }
        }
        //返回文件的保存路径  多个文件路径，逗号隔开
        String paths = sb.toString();
        paths = paths.substring(0,paths.length()-1);
        System.out.println(paths);
        returnMessage.id = 0;
        returnMessage.message = paths;//把路径存储到返回信息中

        return returnMessage;
    }

    //文件上传到七牛具体实现
    private String uploadFileToQiNiu(byte[] uploadBytes,String fileName){

        fileName = "letao//"+fileName;

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;

        try {
            //byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            Auth auth = Auth.create(accessKey,secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(uploadBytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return fileName;//保存成功了就返回文件名
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                    ex2.printStackTrace();
                }
            }
        } catch (Exception ex) {
            //ignore
            ex.printStackTrace();
        }
        return null;
    }
}
